package com.funmi.lizip.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.DeleteRequest;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.entity.Personnel;
import com.funmi.lizip.entity.RangersCollect;
import com.funmi.lizip.entity.dto.personnel.PersonnelAddRequest;
import com.funmi.lizip.entity.dto.personnel.PersonnelQueryRequest;
import com.funmi.lizip.entity.dto.personnel.PersonnelUpdateRequest;
import com.funmi.lizip.entity.dto.rangersCollect.RangersCollectAddRequest;
import com.funmi.lizip.entity.dto.rangersCollect.RangersCollectQueryRequest;
import com.funmi.lizip.entity.dto.rangersCollect.RangersCollectUpdateRequest;
import com.funmi.lizip.entity.enums.PathEnum;
import com.funmi.lizip.entity.vo.PersonnelVo;
import com.funmi.lizip.entity.vo.RangersCollectVo;
import com.funmi.lizip.service.PersonnelService;
import com.funmi.lizip.service.RangersCollectService;
import com.funmi.lizip.utils.MyJsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  巡护采集
 * </p>
 *
 * @author yeyg
 * @since 2022-11-03
 */
@Api(tags = "采集信息模块")
@RestController
@RequestMapping("/rangersCollect")
public class RangersCollectController {

    @Autowired
    private RangersCollectService rangersCollectService;
    @Autowired
    private PersonnelService personnelService;

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "分页获取巡护采集信息")
    @GetMapping("")
    public R rangersCollectPage(RangersCollectQueryRequest request) throws IllegalAccessException {
        // 空字符串设置为null
        RangersCollectQueryRequest rangersCollectQueryRequest = MyJsonUtil.setNullValue(request);

        long current = 1;
        long size = 10;
        RangersCollect rangersCollectQuery = new RangersCollect();

        if (request != null) {
            BeanUtils.copyProperties(rangersCollectQueryRequest, rangersCollectQuery);
            current = request.getPage();
            size = request.getPageSize();
        }
        rangersCollectQuery.setTitle(null);
        QueryWrapper<RangersCollect> queryWrapper = new QueryWrapper<>(rangersCollectQuery);
        queryWrapper.orderByDesc("create_at");
        if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getTitle())){
            queryWrapper.like("title",request.getTitle());
        }

        Page<RangersCollect> rangersCollectPage = rangersCollectService.page(new Page<>(current, size), queryWrapper);

        PageDTO<RangersCollectVo> rangersCollectVoPage = new PageDTO<>(rangersCollectPage.getCurrent(), rangersCollectPage.getSize(), rangersCollectPage.getTotal());
        List<RangersCollectVo> rangersCollectVoList = rangersCollectPage.getRecords().stream().map(personnel -> {
            RangersCollectVo rangersCollectVo = new RangersCollectVo();
            BeanUtils.copyProperties(personnel, rangersCollectVo);
            if(!ObjectUtils.isEmpty(personnel.getFileJson())){
                JSONArray object = new JSONArray();
                JSONArray fileJson = personnel.getFileJson();
                Object[] objects = fileJson.toArray();
                for (Object o : objects) {
                    object.add("RangersCollect" + o);
                }
                rangersCollectVo.setFileJson(object);
            }
            Personnel byId = personnelService.getById(personnel.getRangerid());
            rangersCollectVo.setContact_tel(byId.getContactTel());
            rangersCollectVo.setName(byId.getName());
            return rangersCollectVo;
        }).collect(Collectors.toList());
        rangersCollectVoPage.setRecords(rangersCollectVoList);
        return R.success().data(rangersCollectVoPage);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "新增采集信息")
    @PostMapping("")
    public R rangersCollectAdd(@RequestBody RangersCollectAddRequest request) throws IOException {
        boolean b = rangersCollectService.add(request);
        if (b){
            return R.success().data("新增成功");
        }
        return R.fail();
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "删除采集信息")
    @DeleteMapping("/{id}")
    public R rangersCollectDelete(@RequestBody DeleteRequest request){
        boolean b = rangersCollectService.delete(request);
        if (b){
            return R.success().data("删除成功");
        }
        return R.success().data("删除失败");
    }


    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改采集信息")
    @PutMapping("")
    public R rangersCollectUpdate(@RequestBody HashMap<String, Object> request){
        boolean b = rangersCollectService.updateBy(request);
        if (b){
            return R.success().data("修改成功");
        }
        return R.success().data("修改失败");
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改采集信息参数示例")
    @PutMapping("/testUpdate")
    public R updateEX(@RequestBody RangersCollectUpdateRequest request){
        return R.success();
    }
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "新增采集信息参数示例")
    @PutMapping("/testAdd")
    public R addEX(@RequestBody RangersCollectAddRequest request){
        return R.success();
    }


    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取采集事件详情")
    @GetMapping("/{id}")
    public R rangersCollectAddress(@PathVariable int id ){
        RangersCollect rangersCollect = rangersCollectService.getById(id);
        if (!ObjectUtils.isEmpty(rangersCollect) && !ObjectUtils.isEmpty(rangersCollect.getFileJson())){
            JSONArray layPic = rangersCollect.getFileJson();
            Object[] objects = layPic.toArray();
            List<Object> collect = Arrays.stream(objects).collect(Collectors.toList());
            collect.forEach(fileName ->{
                fileName = "RangersCollect"+"/" + fileName;
            });
            JSONArray array = JSONArray.parseArray(JSON.toJSONString(collect));
            rangersCollect.setFileJson(array);
        }
        RangersCollectVo rangersCollectVo = new RangersCollectVo();
        BeanUtils.copyProperties(rangersCollect, rangersCollectVo);
        rangersCollectVo.setName(personnelService.getNameById(Integer.valueOf(rangersCollect.getRangerid())));
        return R.success().data(rangersCollectVo);
    }


    @ApiOperation(value = "采集信息附件上传")
    @PostMapping(value = "/upload")
    public R upload(@RequestParam(value = "file") MultipartFile[] file){
        ArrayList<String> strings = new ArrayList<>();
        if (!(new File(PathEnum.PATH.getText())).exists()) {
            new File(PathEnum.PATH.getText()).mkdirs();
        }
        Arrays.stream(file).forEach(files -> {
            try {
                files.transferTo(new File(PathEnum.PATH.getText() + "\\" + files.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            strings.add(files.getOriginalFilename());
            }
        );
        return R.success().data(strings);
    }

    @ApiOperation(value = "采集信息excel下载")
    @GetMapping(value = "/excelDownload/{type}")
    public void excel(@PathVariable Integer type, HttpServletResponse response) throws IOException {
        rangersCollectService.excelWrite(type, response);
    }

}

